iT邦幫忙

2023 iThome 鐵人賽

DAY 7
0
自我挑戰組

線上商店串接tappay系列 第 7

javascript 事件回應與網路連線

  • 分享至 

  • xImage
  •  

Java script是幫助我們在網頁中增加使用者互動性和動態效果的語言,只要在html的結構中加入即可使用,一般來說可以在開發人員工具的console視窗中看到執行結果。
我們可以用javascript寫一些簡單的事件處理,例如讓網頁對滑鼠的行為作出回應

 <span class="btn"
            onmouseover="over(this);"onmouseout="out(this);"
            onmousedown="down(this);"onmouseup="up(this);"
            >點我</span> 
        <script>
            function up(elem){
                elem.style.fontWeight="normal";
            }
            function down(elem){
                elem.style.fontWeight="bold";
            }
            function over(elem){
                elem.style.backgroundColor='#ddaaaa';
            }
            function out(elem){
                elem.style.backgroundColor='#ffcccc';
            }
       </script>

URL也就是網址,其實包含通訊協定,主機名和路徑,透過網址我們就有
讓網頁前端取得後端伺服器服務的最基本條件。
URL

AJAX其實就是利用javascript來進行網路連線,例如使用fetch()函式,
步驟包含確認要連線的網址是什麼,建立連線,取得伺服器回應

<button onclick="getData()">連線取得資料</button>
       <script>
        function getData(){
            fetch("https://cwpeng.github.io/live-records-samples/data/products.json").then(function(response){
                return response.json();
            }).then(function(data){
                let result = document.querySelector("#result");
                result.innerHTML="";
                 for(let i=0;i<data.length;i++){
                    let product=data[i];
                    console.log(product.name);
                    result.innerHTML+="<div>"+product.name+","+product.price+","+product.description+"</div>";
                }
            });
        }
       </script>

參考資料

Parts of a URL: A Short Guide

澎澎的課程


上一篇
回應式設計
下一篇
Node.js
系列文
線上商店串接tappay30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言